# -*- coding: utf-8 -*-
from kafka import KafkaProducer
from imutils.video import VideoStream
import requests
import imutils
import numpy as np
import time
import cv2
from PIL import Image
from io import BytesIO
import base64
import json


def publish_video(rtsp, api_url):
   vs = VideoStream(src=rtsp).start()
   time.sleep(2.0)

   print("publishing video...")
   
   i=1
   a=5
   while True:
      i = i + 1
      if i % a == 0:
          frame = vs.read()
          if frame is not None:
              frame = process(frame, api_url)
              cv2.namedWindow('111', flags=cv2.WINDOW_FREERATIO)
              cv2.imshow('111', frame)

              key = cv2.waitKey(1) & 0xFF
              if key == ord("q"):
                  break

   vs.stop()


def process(frame, api_url):
   img = Image.fromarray(frame)
   output_buffer = BytesIO()  # 创建一个BytesIO
   img.save(output_buffer, format='JPEG')  # 写入output_buffer
   byte_data = output_buffer.getvalue()  # 在内存中读取
   image_base64 = base64.b64encode(byte_data).decode()  # 转为BASE64
   data = json.dumps(
      {"image": image_base64, "visual_result": "True", "username": "xsrt", "password": "dGVzdC1wd2QxMjM="})
   headers = {"Content-Type": "application/json"}
   response = requests.post(api_url, data=data, headers=headers)
   result = response.text
   result = json.loads(result)
   try:
      base64_img = result["base64"]
      process_img = base64.b64decode(base64_img)
      img = cv2.imdecode(np.frombuffer(process_img, np.uint8), cv2.IMREAD_COLOR)
      img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
   except:
      img = frame

   return img


def process_list(result):
   for i in result:
      result_i = i
      result_i_bbox = result_i["bbox"]
      for i in range(len(result_i_bbox)):
         result_i_bbox[i] = result_i_bbox[i] * 2
   return result


if __name__ == '__main__':
   rtsp = 0#'D:/work/projects/drone/data/video/秸秆禁燃.mp4'
   api_url = 'http://192.168.20.114:8888/smoke/json'
   publish_video(rtsp, api_url)